const { add } = require('lodash');
const _util = require('../../util/util.js');
require('./index.css');

const userInfo = localStorage.getItem('userInfo');
const user = JSON.parse(userInfo);

let address = null;

function updateSelectAddress(){
    address = $(".address.active").data("id"); // 获取当前选中的地址id
}

// 全局函数，供动态生成元素调用
window.selectAddress = function (addressElement) {
    document.querySelectorAll('.address').forEach(addr => addr.classList.remove('active'));
    addressElement.classList.add('active');
};

window.deleteAddress = function (addressId, event) {
    updateSelectAddress();
    event.stopPropagation();
    if (confirm('确认删除此地址吗？')) {
        fetch(_util.getServerURL(`order/addresses/${addressId}`), { method: 'DELETE' })
            .then(res => res.json())
            .then(data => {
                if (data.status === 0) {
                    alert('删除成功！');
                    getAddressList();
                } else {
                    alert('删除失败：' + data.message);
                }
            }).catch(console.error);
    }
};

// 模态框和表单逻辑
function initModal() {
    const modal = document.getElementById('addAddressModal');
    const closeBtn = modal.querySelector('.close');
    const form = document.getElementById('addAddressForm');

    // 关闭模态框
    closeBtn.onclick = () => { modal.style.display = 'none'; };
    window.onclick = e => { if (e.target === modal) modal.style.display = 'none'; };


    // 表单提交
    form.onsubmit = function (e) {
        e.preventDefault();

        updateSelectAddress();

        const payload = {
            userId: userId,
            province: this.province.value,
            city: this.city.value,
            district: this.district.value,
            detailAddress: this.detailAddress.value,
            phoneNumber: this.phoneNumber.value,
            receiverName: this.receiverName.value,
            isDefault: this.isDefault.checked ? 1 : 0
        };
        fetch(_util.getServerURL(`order/addresses`), {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload)
        }).then(res => res.json())
            .then(() => {
                modal.style.display = 'none';
                getAddressList();
            }).catch(console.error);
    };
}

// 获取并渲染地址列表
// const user = JSON.parse(localStorage.getItem('userInfo')) || {};
const userId = user.id;

async function getAddressList() {
    try {
        const res = await fetch(_util.getServerURL(`order/singleOrder?userId=${userId}`));
        const result = await res.json();
        renderAddressList(result.data || []);
    } catch (err) {
        console.error('获取地址失败：', err);
    }
}

function renderAddressList(addressList) {
    const container = document.getElementById('addressListContainer');
    container.innerHTML = ''; // 清空现有内容

    addressList.forEach(addr => {
        const div = document.createElement('div');
        div.className = addr.isDefault ? 'address active' : 'address';
        div.dataset.id = addr.id;

        if (addr.isDefault) {
            address = addr.id;
        }

        div.innerHTML = `
            <div class="address-info" data-id="${addr.id}">
                <span class="province">${addr.province}</span>省
                <span class="city">${addr.city}</span>市
                <span class="district">${addr.district}</span>区<br>
                详细地址：<span class="detail">${addr.detailAddress}</span><br>
                收件人：<span class="receiver">${addr.receiverName}</span><br>
                电话：<span class="phone">${addr.phoneNumber}</span>
                ${addr.isDefault ? '<div class="tag-default">默认地址</div>' : ''}
            </div>
            <div class="address-actions">
                <button onclick="deleteAddress(${addr.id}, event)">删除</button>
            </div>
        `;

        // 点击选中地址
        div.onclick = () => {
            document.querySelectorAll('.address').forEach(addr => addr.classList.remove('active'));
            div.classList.add('active');
            address = div.dataset.id;
        };

        container.appendChild(div);
    });

    // 添加“使用新地址”按钮
    const addBtn = document.createElement('div');
    addBtn.className = 'address add-new';
    addBtn.innerText = '+ 使用新地址';
    addBtn.onclick = () => {
        document.getElementById('addAddressModal').style.display = 'block';
    };
    container.appendChild(addBtn);
}


//商品列表
 async function initOrder() {

    //从购物车来还是单独来
    var flag = localStorage.getItem('fromCart');
    console.log(flag);
    const tbody = document.getElementById("cartItemsBody");

    // 清空现有内容（可选）
    tbody.innerHTML = "";

    if(flag === '1'){
        console.log('渲染多个 ...... ');
        var result = await getCartOrder();
        console.log(result);
        var items = result.data.cartItemList;
        console.log(items);
        var total = 0;

        items.forEach(item => {
            const row = document.createElement("tr");
            row.innerHTML = `
                <td>
                    <img src="${item.url}" alt="${item.name}" style="width: 100px; height: auto;"><br>
                    <span>${item.name}</span>
                </td>
                <td>¥<span>${item.price}</span></td>
                <td>${item.itemNum}</td>
                <td>¥<span>${item.price * item.itemNum}</span></td>
            `;
            tbody.appendChild(row);
            total += item.price;
        });

        $('.price').html(`￥<span>${total}</span>`)

    }else{
        console.log('渲染单个 ...... ');
        var itemJson = localStorage.getItem('selectedItem');
        var item = JSON.parse(itemJson)

        const row = document.createElement("tr");
        row.innerHTML = `
            <td>
                <img src="${item.url}" alt="${item.name}" style="width: 100px; height: auto;"><br>
                <span>${item.name}</span>
            </td>
            <td>¥<span>${item.price}</span></td>
            <td>1</td>
            <td>¥<span>${item.price}</span></td>
        `;

        tbody.appendChild(row);

        $('.price').html(`￥<span>${item.price}</span>`)
    }

    
}


async function getCartOrder() {
    try {
        const res = await fetch(_util.getServerURL(`order/cartOrder?userId=${userId}`));
        var result = await res.json();
        return result;
    } catch (err) {
        console.error('获取CartOrde失败：', err);
    }
    
}


// 初始化
document.addEventListener('DOMContentLoaded', async () => {
    initModal();
    await getAddressList();
    await initOrder();

    // 确保所有数据加载完成后再执行提交逻辑初始化
    setTimeout(() => {
        require('./submitOrder.js');
    }, 0);
    console.log('address'+address)
});

